const axios = require('axios');
const app_id = "cli_a4cd42b6bcf8900d"
const app_secret = "pWtoPe8Usz2XIjg06TgVEbOQZJruIkrx"

// 获取app的token
// getAppToken 定义为一个异步函数，返回一个promise对象（reslove处理请求成功，reject处理异常）
const getAppToken = async function () {
  return new Promise(async (reslove, reject) => {
    try {
      const res = await axios({
        method: 'post',
        url: 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal',
        headers: { 'Content-Type': "application/json; charset=utf-8" },
        data: {
          app_id,
          app_secret
        }
      })
      reslove(res.data.tenant_access_token)
    }
    catch (err) {
      reject(err)
    }
  })
}

// 携带机器人token获取机器人所在的群聊id
const getGroupId = async function (appToken) {
  return new Promise(async (reslove, reject) => {
    try {
      const res = await axios({
        method: 'get',
        url: 'https://open.feishu.cn/open-apis/im/v1/chats',
        headers: { Authorization: `Bearer ${appToken}` }
      })
      reslove(res.data)
    }
    catch (err) {
      reject(err)
    }
  })
}

// 携带机器人token向群组发送消息
const sendMes = async function (groupId, appToken, msg_type, content) {
  return new Promise(async (reslove, reject) => {
    try {
      const res = await axios({
        method: 'post',
        url: 'https://open.feishu.cn/open-apis/im/v1/messages',
        headers: {
          Authorization: `Bearer ${appToken}`,
          'Content-Type': "application/json; charset=utf-8"
        },
        data: {
          "receive_id": groupId,
          msg_type,
          content
        },
        params: {
          "receive_id_type": "chat_id"
        }
      })
      reslove(res.data)
    }
    catch (err) {
      reject(err)
    }
  })
}

const sendText = async function (msg_type, content) {
  // 获取appToken
  let appToken = await getAppToken()
  // 获取群组信息
  let groupMes = await getGroupId(appToken)
  // 获取群组Id
  let groupId = groupMes.data.items[0].chat_id
  // 调用向群组发送消息的接口
  sendMes(groupId, appToken, msg_type, content)
}

module.exports = sendText
